package com.cff.boot.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.cff.boot.dao.UserInfoDao;
import com.cff.boot.domain.UserInfo;
import com.cff.boot.domain.UserRole;

@Service
public class CustomUserDetailsService implements UserDetailsService {
	@Autowired
	private UserInfoDao userInfoDao;

	@Override
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
		UserInfo userInfo = userInfoDao.findByUserName(userName);
		if (null == userInfo) {
			throw new UsernameNotFoundException("UserName " + userName + " not found");
		}
		// SecurityUser实现UserDetails并将SUser的Email映射为username
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		for (UserRole ur : userInfo.getUserRoles()) {
			String name = ur.getRole();
			GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(name);
			authorities.add(grantedAuthority);
		}
		return new User(userInfo.getUserName(), userInfo.getPasswd(), authorities);
	}

}
